package bll

import (
	"context"
	"manager/auth"
	"manager/utils"

	"manager/event"
	"manager/model"
	"manager/model/entity"
	"manager/store"
	"manager/store/postgres"
	"time"
)

type repair struct {
	iRepair store.IRepair
}

var Repair = &repair{
	iRepair: postgres.Repair,
}

func (a *repair) init() func() {
	return func() {}
}

func (a *repair) onEvent(*event.Data) {}

// Create 创建
func (a *repair) Create(ctx context.Context, in *model.RepairCreateRequest) error {
	var (
		err error
	)

	in.Reportman, _ = auth.ContextUserID(ctx)
	in.OrderNo = utils.Generate(time.Now())

	// 车主ID
	managerId := UserEbike.GetManagerByBikeId(in.EbikeId)

	// 获取车辆信息
	bike, err := Ebike.BikeInfo(context.WithValue(context.Background(), auth.AuthUserKey, managerId), in.EbikeId)
	if err != nil {
		return err
	}

	// 设置车辆类型信息
	in.EbikeTypeName = bike.Name
	in.EbikeTypeId = bike.TypeID
	in.EbikeTypeImage = bike.Photo

	// 构建创建现场数据
	c := buildRepair(in)
	_, err = a.iRepair.Create(ctx, c)
	return err
}

// Update 更新
func (a *repair) Update(ctx context.Context, in *model.RepairUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt

	if in.Reportman != nil {
		dict["reportman"] = in.Reportman
	}

	if in.EbikeId != nil {
		dict["ebike_id"] = in.EbikeId
	}

	if in.FaultId != nil {
		dict["fault_id"] = in.FaultId
	}

	if in.FaultName != nil {
		dict["fault_name"] = in.FaultName
	}

	if in.FaultTypeId != nil {
		dict["fault_type_id"] = in.FaultTypeId
	}

	if in.FaultTypeName != nil {
		dict["fault_type_name"] = in.FaultTypeName
	}

	if in.EbikeTypeId != nil {
		dict["ebike_type_id"] = in.EbikeTypeId
	}

	if in.EbikeTypeName != nil {
		dict["ebike_type_name"] = in.EbikeTypeName
	}

	if in.EbikeTypeImage != nil {
		dict["ebike_type_image"] = in.EbikeTypeImage
	}

	if in.Other != nil {
		dict["other"] = in.Other
	}

	if in.Type != nil {
		dict["type"] = in.Type
	}

	if in.Coordinate != nil {
		dict["coordinate"] = in.Coordinate
	}

	if in.Photo != nil {
		dict["photo"] = in.Photo
	}

	if in.OrderNo != nil {
		dict["order_no"] = in.OrderNo
	}

	if in.Status != nil {
		dict["status"] = in.Status
	}

	if in.Repairman != nil {
		dict["repairman"] = in.Repairman
	}

	if in.Price != nil {
		dict["price"] = in.Price
	}

	if in.StoreId != nil {
		dict["store_id"] = in.StoreId
	}

	if in.Desc != nil {
		dict["desc"] = in.Desc
	}

	if in.RepairAt != nil {
		dict["repair_at"] = in.RepairAt
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here

	return a.iRepair.Update(ctx, in.Id, dict)
}

// Delete 删除
func (a *repair) Delete(ctx context.Context, in *model.RepairDeleteRequest) error {
	return a.iRepair.Delete(ctx, in.Id)
}

// List 列表查询
func (a *repair) List(ctx context.Context, in *model.RepairListRequest) (*model.RepairListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.Repair
		out   = &model.RepairListResponse{}
	)

	// todo: check the in is required
	if auth.ContextOs(ctx) != "web" {
		userId, _ := auth.ContextUserID(ctx)
		in.Reportman = &userId
	}

	// 获取列表
	if total, list, err = a.iRepair.List(ctx, in); err != nil {
		return nil, err
	}

	// 获取门店信息
	var storeIds []int64
	for i := 0; i < len(list); i++ {
		storeIds = append(storeIds, list[i].StoreId)
	}

	// 获取门店信息
	_, storesMap, _ := StoreServer.GetStoreListByIds(ctx, storeIds)

	out.Total = total
	out.List = model.RepairsEntityToDto(list)

	// 设置门店名称
	for i := 0; i < len(out.List); i++ {
		if _, ok := storesMap[out.List[i].StoreId]; ok {
			out.List[i].StoreName = storesMap[out.List[i].StoreId].Name
		}
	}

	return out, nil
}

// Find 列表查询
func (a *repair) Find(ctx context.Context, in *model.RepairInfoRequest) (*model.RepairInfo, error) {
	var (
		err  error
		data *entity.Repair
		out  = &model.RepairInfo{}
	)

	if data, err = a.iRepair.Find(ctx, in.Id); err != nil {
		return nil, err
	}

	out = model.RepairEntityToDto(data)
	return out, nil
}

// buildRepair 构建创建数据现场
func buildRepair(in *model.RepairCreateRequest) *entity.Repair {
	// todo: check the entity is required
	return &entity.Repair{

		Reportman: in.Reportman,

		EbikeId: in.EbikeId,

		FaultId: in.FaultId,

		FaultTypeId: in.FaultTypeId,

		FaultName:      in.FaultName,
		FaultTypeName:  in.FaultTypeName,
		EbikeTypeId:    in.EbikeTypeId,
		EbikeTypeName:  in.EbikeTypeName,
		EbikeTypeImage: in.EbikeTypeImage,

		Other: in.Other,

		Type: in.Type,

		Coordinate: in.Coordinate,

		Photo: in.Photo,

		OrderNo: in.OrderNo,

		Status: in.Status,

		Repairman: in.Repairman,

		Price: in.Price,

		StoreId: in.StoreId,

		Desc: in.Desc,

		RepairAt: in.RepairAt,

		CreatedAt: time.Now().Unix(),

		UpdatedAt: time.Now().Unix(),
	}
}
